import 'dart:async';
import 'package:flutter/material.dart';
import 'package:honeypotflutter/public/public_untilController.dart';
import 'package:honeypotflutter/publicBussine/bussine_colors.dart';
import 'package:honeypotflutter/publicBussine/bussine_font.dart';

class LoginTimer extends StatefulWidget {
  final TextEditingController? controller;
  final FocusNode? node;
  final Function()? codeAction;
  final HLUntilController? untilController;
  const LoginTimer({super.key, this.controller, this.node, this.codeAction, this.untilController});
  @override
  State<LoginTimer> createState() => _LoginTimerState();
}

class _LoginTimerState extends State<LoginTimer> {
  String _hint = "发送验证码";

  Timer? _timer;

  bool _isAction = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.untilController != null) {
      widget.untilController!.action = () {
        if (_timer != null && _timer!.isActive) {
          return;
        }
        if (_timer != null) {
          _timer?.cancel();
          _timer = null;
        }
        _hint = "60 秒";
        int _time = 60;
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          if (_time < 0) {
            setState(() {
              _hint = "发送验证码";
            });
            _isAction = true;
            timer.cancel();
            return;
          }
          _isAction = false;
          setState(() {
            _hint = "${_time} s";
          });
          _time -= 1;
        });
      };
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 10),
      child: TextField(
          controller: widget.controller,
          focusNode: widget.node,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
              hintText: "请输入验证码",
              hintStyle: TextStyle(fontSize: MGFont.textFont2, color: MGColors.text3Color),
              enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: MGColors.splitColor)),
              focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: MGColors.splitColor)),
              suffixIcon: TextButton(
                  onPressed: () {
                    if (!_isAction) {
                      return;
                    }
                    if (widget.codeAction != null) {
                      widget.codeAction!();
                    }
                  },
                  child: Text(_hint,
                      style: TextStyle(
                        color: MGColors.themeColor,
                        fontSize: MGFont.textFont1,
                      )))),
          style: TextStyle(
            fontSize: MGFont.textFont1,
            color: MGColors.text1Color,
          )),
    );
    ;
  }
}
